<script lang="tsx" setup>
import type { FormRules } from 'naive-ui';
import { onMounted, reactive, ref } from 'vue';
import { profile, updateUserProfile } from '@/service/api/system/user';
import { useAuthStore } from '@/store/modules/auth';
import type { UserVO } from '@/service/types/system';
import { useNaiveForm } from '@/hooks/common/form';
import Cropper from '@/components/custom/cropper.vue';
import { useBoolean } from '~/packages/hooks/src';
import PasswordForm from './password-form.vue';
const authStore = useAuthStore();
type Model = Pick<UserVO, 'nickName' | 'phonenumber' | 'email' | 'sex' | 'remark'>;
const { bool: visible, setTrue: openModal } = useBoolean();

const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
  return {
    nickName: '',
    phonenumber: '',
    remark: '',
    sex: '0',
    email: ''
  };
}
const showLoading = ref<boolean>(false);
const haderText = ref<string>('');
const userInfo = ref<UserVO>();
const imageUrl = ref<string>('');

const getUserProfile = async () => {
  showLoading.value = true;
  const { data, error } = await profile();
  showLoading.value = false;
  if (!error) {
    const dataInfo = data?.data;
    imageUrl.value = dataInfo.user.avatar;
    userInfo.value = dataInfo.user;
    haderText.value = `${authStore.userInfo.company.companyName} | ${authStore.userInfo.user.deptName} | ${dataInfo.postGroup} | ${dataInfo.roleGroup}`;
    handleInitModel(dataInfo.user);
  }
};

const { formRef, validate, restoreValidation } = useNaiveForm();
const rules: FormRules = {
  nickName: {
    required: true,
    message: '昵称不能为空',
    trigger: 'blur'
  },
  sex: {
    required: true,
    message: '性别不能为空',
    trigger: 'blur'
  },
  email: {
    required: true,
    message: '邮箱不能为空',
    trigger: 'blur'
  },
  // deviceType: createRequiredRule('设备类型不能为空'),
  // roleSort: createRequiredRule('排序不能为空'),
  phonenumber: {
    required: true,
    message: '手机号不能为空',
    trigger: 'blur'
  }
};

async function handleInitModel(user: UserVO) {
  Object.assign(model, user);
}

onMounted(() => {
  restoreValidation();
  getUserProfile();
});

const reset = () => {
  Object.assign(model, userInfo.value);
};
const loading = ref<boolean>(false);
const submit = async () => {
  await validate();
  loading.value = true;
  const { ...params } = model;
  // 提交表单
  const { data, error } = await updateUserProfile(params as UserVO);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
  }
};
// 上传头像
const uploadAvatar = () => {
  imageUrl.value = userInfo.value?.avatar as string;
  openModal();
};
</script>

<template>
  <NSpin :show="showLoading">
    <div class="min-h-500px flex flex-col flex-gap-10px p-10px">
      <div style="background-size: cover" class="header_bg h-144px flex flex-items-center pl-30px">
        <div class="flex flex-gap-15px flex-items-center">
          <div class="avatar-container">
            <!-- 头像 -->
            <NAvatar round :size="70" :src="userInfo?.avatar" class="avatar-image" />
            <!-- 遮罩层 -->
            <div class="overlay" @click="uploadAvatar">
              <!-- 图标 -->
              <SvgIcon class="cursor-pointer font-size-5 color-white" local-icon="phonto" />
            </div>
          </div>
          <div>
            <div class="font-width-800 font-size-18px">{{ userInfo?.userName }}</div>
            <div class="mt-8px font-size-12px text-gray-400">
              <NEllipsis class="m-w-200px" :line-clamp="2">
                {{ haderText }}
              </NEllipsis>
            </div>
          </div>
        </div>
      </div>
      <div>
        <NTabs
          type="line"
          pane-wrapper-style="margin: 0 -4px;"
          pane-style="padding-left: 4px; padding-right: 4px; box-sizing: border-box;"
          animated
          :bar-width="300"
          class="card-tabs"
        >
          <NTabPane name="chap1" tab="个人信息">
            <NForm ref="formRef" :model="model" :rules="rules">
              <NGrid responsive="screen" item-responsive>
                <NFormItemGi span="24 s:24 m:24" label="用户昵称" path="nickName">
                  <NInput v-model:value="model.nickName" placeholder="用户昵称" />
                </NFormItemGi>
                <NFormItemGi span="24 s:24 m:24" label="手机号码" path="phonenumber">
                  <NInput v-model:value="model.phonenumber" placeholder="手机号码" />
                </NFormItemGi>
                <NFormItemGi span="24 s:24 m:24" label="邮箱" path="email">
                  <NInput v-model:value="model.email" placeholder="邮箱" />
                </NFormItemGi>
                <NFormItemGi span="24 s:24 m:24" label="性别" path="sex">
                  <NRadioGroup v-model:value="model.sex" name="sex">
                    <NSpace>
                      <NRadio value="0">男</NRadio>
                      <NRadio value="1">女</NRadio>
                    </NSpace>
                  </NRadioGroup>
                </NFormItemGi>
                <NFormItemGi span="24 s:24 m:24" label="个性签名" path="remark" feedback-style="min-height: 0px;">
                  <NInput v-model:value="model.remark" type="textarea" placeholder="个性签名" />
                </NFormItemGi>
                <NFormItemGi span="24 s:24 m:24">
                  <NSpace class="w-full" justify="start">
                    <NButton @click="reset">
                      {{ $t('common.reset') }}
                    </NButton>
                    <NButton type="primary" :loading="loading" @click="submit">保存</NButton>
                  </NSpace>
                </NFormItemGi>
              </NGrid>
            </NForm>
          </NTabPane>
          <NTabPane name="chap2" tab="修改密码">
            <PasswordForm />
          </NTabPane>
        </NTabs>
      </div>
    </div>
    <Cropper v-model:visible="visible" :image-url="imageUrl" @submitted="getUserProfile" />
  </NSpin>
</template>

<style lang="scss" scoped>
.header_bg {
  width: 100%;
  background: url('@/assets/svg-icon/avatar_bg.svg') no-repeat;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

// .avatar-image {
//   border-radius: 50%;
// }

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 70px;
  height: 70px;
  background-color: rgba(0, 0, 0, 0.6);
  /* 半透明遮罩 */
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  /* 平滑过渡 */
}

.avatar-container:hover .overlay {
  opacity: 1;
  /* 悬浮时显示遮罩 */
}
</style>
